package com.amigo;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.amigo.helper.Constants;
import com.amigo.helper.JsonFileUtility;
import com.amigo.helper.ServiceHandler;
import com.amigo.views.SquareImageView;

public class CompleteProfile extends Activity {
	ImageView img;
	List<String> filepaths;
	LinearLayout parent;
	private String url = Constants.getBaseUrl() + "updateUser";
	private String Message, Token;
	boolean Success;
	private String url_image = Constants.getBaseUrl() + "uploadProfilePic";
	private String TokenFromDB, DB_USER;
	private String fullname, email, dob, interests, gender, location, about;
	JSONObject jObj;
	private static final int SELECT_PHOTO = 100;
	private EditText About, Location;
	private boolean user_db_exist = false;

	ProgressDialog ringProgressDialog = null;
	
	String responsef ;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_complete_profile);

		parent = (LinearLayout) findViewById(R.id.horizontal_image_ll);
		About = (EditText) findViewById(R.id.about_input);
		Location = (EditText) findViewById(R.id.location);

		filepaths = new ArrayList<String>();

		TokenFromDB = JsonFileUtility.ReadJsonData(Constants.TAG_UserGUID);
		try {
			jObj = new JSONObject(
					JsonFileUtility.ReadJsonData(Constants.TAG_UserObject));
			fullname = jObj.getString("name");
			email = jObj.getString("email");
			dob = jObj.getString("dob");
			gender = jObj.getString("gender");
			interests = jObj.getString("interests");
			user_db_exist = true;

		} catch (JSONException e) {
			user_db_exist = false;
			e.printStackTrace();
		}

		final Button Register = (Button) findViewById(R.id.Register);
		Register.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				addfilepathstoList();

				Register.setEnabled(false);

				if (checkblanks()) {
					location = Location.getText().toString();
					about = About.getText().toString();
					new UpdateUserProfile().execute();
				} else {
					Register.setEnabled(true);
				}

			}
		});

	}

	private boolean checkblanks() {
		boolean result = true;
		if (Location.getText().toString().isEmpty()) {
			Location.setError("This Field Cannot be Left Blank");
			result = false;
		}

		return result;
	}

	public void opengallery(View v) {
		img = (ImageView) v;

		Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
		photoPickerIntent.setType("image/*");
		startActivityForResult(photoPickerIntent, SELECT_PHOTO);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent imageReturnedIntent) {
		super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

		switch (requestCode) {
		case SELECT_PHOTO:
			if (resultCode == RESULT_OK) {
				Uri selectedImage = imageReturnedIntent.getData();
				String imagePath = getImagePath(selectedImage);
				img.setTag(imagePath);

				try {

					Bitmap yourSelectedImage = decodeUri(selectedImage);
					img.setImageBitmap(yourSelectedImage);
					FrameLayout frame = (FrameLayout) img.getParent();
					ImageView remove_img = new ImageView(this);
					FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
							LayoutParams.WRAP_CONTENT,
							LayoutParams.WRAP_CONTENT);
					params.gravity = Gravity.RIGHT;
					remove_img.setLayoutParams(params);
					remove_img.setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.remove_image));
					remove_img.bringToFront();
					remove_img.setOnClickListener(new View.OnClickListener() {

						@Override
						public void onClick(View v) {
							remove_image(v);

						}
					});
					frame.addView(remove_img);
					addotherimage();

				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		}

	}

	private void addotherimage() {

		if (parent.getChildCount() < 8 && isdefaultsomewhereelse()) {

			LinearLayout gap = new LinearLayout(this);
			LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			gap.setPadding(10, 0, 10, 0);
			gap.setLayoutParams(p);

			FrameLayout frame = new FrameLayout(this);
			FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			params.setMargins(10, 0, 10, 0);
			frame.setLayoutParams(params);
			frame.setBackgroundDrawable(getResources().getDrawable(
					R.drawable.roundedcorners));
			frame.setPadding(10, 10, 10, 10);

			SquareImageView image = new SquareImageView(this);
			image.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					opengallery(v);

				}
			});
			image.setLayoutParams(params);
			image.setImageDrawable(getResources().getDrawable(
					R.drawable.add_more_dp));
			image.setTag(Constants.Default_Image_Tag);
			frame.addView(image);
			parent.addView(gap);
			parent.addView(frame);
		}

	}

	private Bitmap decodeUri(Uri SelectedImage) throws FileNotFoundException {

		// Decode image size
		BitmapFactory.Options o = new BitmapFactory.Options();
		o.inJustDecodeBounds = true;
		BitmapFactory.decodeStream(
				getContentResolver().openInputStream(SelectedImage), null, o);

		// The new size we want to scale to
		final int REQUIRED_SIZE = 180;

		// Find the correct scale value. It should be the power of 2.
		int width_tmp = o.outWidth, height_tmp = o.outHeight;
		int scale = 1;
		while (true) {
			if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) {
				break;
			}
			width_tmp /= 2;
			height_tmp /= 2;
			scale *= 2;
		}

		// Decode with inSampleSize
		BitmapFactory.Options o2 = new BitmapFactory.Options();
		o2.inSampleSize = scale;

		return BitmapFactory.decodeStream(
				getContentResolver().openInputStream(SelectedImage), null, o2);

	}

	private String getImagePath(Uri selectedImage) {

		String[] filePathColumn = { MediaStore.Images.Media.DATA };

		Cursor cursor = getContentResolver().query(selectedImage,
				filePathColumn, null, null, null);
		cursor.moveToFirst();

		int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
		String filePath = cursor.getString(columnIndex);
		cursor.close();
		return filePath;
	}

	public void prev(View v) {
		Intent i = new Intent(this, SignUp.class);
		startActivity(i);
		overridePendingTransition(android.R.anim.slide_in_left,
				android.R.anim.slide_out_right);
		finish();
	}

	private void addfilepathstoList() {
		for (int i = 0; i < parent.getChildCount(); i++) {
			View v = parent.getChildAt(i);
			if (v instanceof FrameLayout) {
				ViewGroup childofparent = (ViewGroup) v;
				SquareImageView img = (SquareImageView) childofparent
						.getChildAt(0);
				String imagepath = img.getTag().toString();
				if (!imagepath.equals(Constants.Default_Image_Tag)) {
					filepaths.add(imagepath);
				}
			}
		}
	}

	private boolean isdefaultsomewhereelse() {
		String imagepath = null;
		for (int i = 0; i < parent.getChildCount(); i++) {

			View v = parent.getChildAt(i);
			if (v instanceof FrameLayout) {
				ViewGroup childofparent = (ViewGroup) v;
				SquareImageView img = (SquareImageView) childofparent
						.getChildAt(0);
				imagepath = img.getTag().toString();

			}
		}
		return !imagepath.equals(Constants.Default_Image_Tag);
	}

	public void remove_image(View v) {

		View frametoberemoved = (View) v.getParent();
		ViewGroup fosterparent = parent;
		int indexdeterminer = fosterparent.indexOfChild(frametoberemoved) - 1;
		if (parent.getChildCount() > 2) {
			parent.removeView(frametoberemoved);
			try {
				parent.removeViewAt(indexdeterminer);

			} catch (Exception e) {

			}
		}

		addotherimage();

	}

	private class UploadUserPic extends AsyncTask<List<String>, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

		}

		@Override
		protected Void doInBackground(List<String>... args) {
			
			HttpClient httpClient = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpPost httpPost = new HttpPost(url_image);

			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("userId", TokenFromDB));

			try {
				MultipartEntity entity = new MultipartEntity(
						HttpMultipartMode.BROWSER_COMPATIBLE);

				for (int j = 0; j < args[0].size(); j++) {
					entity.addPart("userId", new StringBody(TokenFromDB));
					entity.addPart("image", new FileBody(new File(args[0]
							.get(j).toString())));
					httpPost.setEntity(entity);

					HttpResponse response = httpClient.execute(httpPost,
							localContext);
					Log.d("response", response.toString());

					HttpEntity httpEntity = response.getEntity();
					responsef = EntityUtils.toString(httpEntity);
					Log.d("responsef", responsef);

				}
				JSONObject jsonObj = new JSONObject(responsef);
				Success = jsonObj.getBoolean("success");
				Message = jsonObj.getString("message");
			//	Token = jsonObj.getString("token");

				if (Success == true) {
					
					JSONObject user = jsonObj.getJSONObject("user");
					DB_USER = user.toString();

				}

			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			
			JsonFileUtility
			.CreateAndSaveFile(Constants.TAG_UserObject, DB_USER);
			
			if (ringProgressDialog.isShowing()) {
				ringProgressDialog.dismiss();

			}

		
			startActivity(new Intent(CompleteProfile.this, Dashboard.class));

		}

	}

	private class UpdateUserProfile extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			ringProgressDialog = ProgressDialog.show(CompleteProfile.this,
					"Signing Up", "Just a few moments will get things going",
					true);
			ringProgressDialog.setCancelable(false);

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// Creating service handler class instance
			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("id", TokenFromDB));
			if (user_db_exist) {
				params.add(new BasicNameValuePair("email", email));
				params.add(new BasicNameValuePair("name", fullname));
				params.add(new BasicNameValuePair("dob", dob));
				params.add(new BasicNameValuePair("gender", gender));
				params.add(new BasicNameValuePair("interests", interests));
			}
			params.add(new BasicNameValuePair("location", location));
			params.add(new BasicNameValuePair("about", about));
			// Making a request to url and getting response
			String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST,
					params);

			Log.d("Response: ", "> " + jsonStr);

			if (jsonStr != null) {
				try {

					JSONObject jsonObj = new JSONObject(jsonStr);

					Success = jsonObj.getBoolean("success");
					Message = jsonObj.getString("message");

				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				Log.e("ServiceHandler", "Couldn't get any data from the url");
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);

			if (Success == true) {
				JsonFileUtility.CreateAndSaveFile(Constants.TAG_UserGUID,
						TokenFromDB);

				new UploadUserPic().execute(filepaths);

			}

		}

	}

}
